package com.alinks.modbus.core.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

public final class ASCIIUtil {

    public static String convertStringToHex(String str){

        char[] chars = str.toCharArray();

        StringBuffer hex = new StringBuffer();
        for(int i = 0; i < chars.length; i++){
            hex.append(Integer.toHexString((int)chars[i]));
        }

        return hex.toString();
    }

    public static String convertHexToString(String hex){

        StringBuilder sb = new StringBuilder();
        StringBuilder temp = new StringBuilder();

        //49204c6f7665204a617661 split into two characters 49, 20, 4c...
        for( int i=0; i<hex.length()-1; i+=2 ){

            //grab the hex in pairs
            String output = hex.substring(i, (i + 2));
            //convert hex to decimal
            int decimal = Integer.parseInt(output, 16);
            //convert the decimal to character
            sb.append((char)decimal);

            temp.append(decimal);
        }

        return sb.toString();
    }

    public static byte[] shortAsciiToBytes(short b) {
        return new byte[] {
                byteAsciiToByte((byte) (b >> 12 & 0xf)),
                byteAsciiToByte((byte) (b >> 8 & 0xf)),
                byteAsciiToByte((byte) (b >> 4 & 0xf)),
                byteAsciiToByte((byte) (b & 0xf))
        };
    }

    public static byte[] byteAsciiToBytes(byte b) {
        return new byte[] {
                byteAsciiToByte((byte) (b >> 4 & 0xf)),
                byteAsciiToByte((byte) (b & 0xf))
        };
    }

    public static byte byteAsciiToByte(byte b) {
        byte[] ascByte = Integer.toHexString(b).toUpperCase().getBytes();
        return ascByte[0];
    }


        public static void main(String[] args) {
        System.out.println(convertStringToHex("01030000000AF2"));
        System.out.println( Integer.toHexString(byteAsciiToByte((byte)-14)));
        System.out.println( convertHexToString("3a30313033303030303030304146320d0a"));
        byte[] b = byteAsciiToBytes((byte) -14);
            System.out.println(Integer.toHexString(b[0]));
            System.out.println(Integer.toHexString(b[1]));
//            System.out.println(Integer.toHexString(b[2]));
//            System.out.println(Integer.toHexString(b[3]));

        String hex = "3a30313033303030303030304146320d0a";

    }
}
